<script setup>

import {ref, onMounted, watch, computed} from 'vue';
import axios from "axios";
import { message } from 'ant-design-vue';
import moment from "moment"

// 查询
const pageSize = ref(10);
const pageNo = ref(1)
const items = ref([]);
const loading = ref(true);
const confirmLoading = ref(false);
const totalItems = ref(0);
const pagination = computed(() => ({
    total: totalItems.value,
    current: pageNo.value,
    pageSize: pageSize.value
})) 
const queryParams = ref({
    orderNumber: "",
    startTime: "",
    endTime: ""
});
const columns = ref([
    {
        title: "返点清单编码",
        dataIndex: "orderNumber",
        key: 'orderNumber',
        resizable: true
    },
    {
        title: "返点清单名称",
        dataIndex: "orderName",
        key: 'orderName',
        resizable: true
    },
    {
        title: "上传时间",
        dataIndex: "createTime",
        key: 'createTime',
        resizable: true
    },
    {
        title: "修改记录",
        dataIndex: "updateTime",
        key: 'updateTime',
        resizable: true
    },
    {
        title: "含税金额(元)",
        dataIndex: "taxTotalAmount",
        key: 'taxTotalAmount',
        align: "center"
    },
    {
        title: "返点金额(元)",
        dataIndex: "pointAmount",
        key: 'pointAmount',
        align: "center"
    },
    {
        title: "实返总额(元)",
        dataIndex: "trueAmount",
        key: 'trueAmount',
        align: "center"
    },
    {
        title: "未返总额(元)",
        dataIndex: "unAmount",
        key: 'unAmount',
        align: "center"
    },
    {
        title: "操作人员",
        dataIndex: "username",
        key: 'username',
        align: "center"
    },
    {
        title: "操作",
        dataIndex: "action"
    }
])
const addList = ref([])
//计算无税总额=单价*数量
//计算含税总额=单价*数量*(1+税率)
//税额就是含税总额-无税总额
//计算返点金额=无税总额*返点率
////如果没有结算金额，则自动计算结算金额。计算结算金额=含税总额-返点金额

//无税均价就是单价
//含税均价就是含税单价
const columnsAdd = ref([
    {
        title: "商品名",
        dataIndex: "goodsName",
        key: 'goodsName',
        fixed: "left",
        resizable: true,
        ellipsis: true
    },
    {
        title: "购进日期",
        dataIndex: "buyDate",
        key: 'buyDate',
        resizable: true
    },
    {
        title: "通用名称",
        dataIndex: "commonName",
        key: 'commonName',
        resizable: true
    },
    {
        title: "供应商名称",
        dataIndex: "supplierName",
        key: 'supplierName',
        resizable: true
    },
    {
        title: "随货同行联号",
        dataIndex: "widthGoodsNumber",
        key: 'widthGoodsNumber',
        resizable: true,
        ellipsis: true
    },
    {
        title: "购进单号",
        dataIndex: "buyNumber",
        key: 'buyNumber',
        resizable: true
    },
    {
        title: "批号",
        dataIndex: "batchNumber",
        key: 'batchNumber',
        align: 'center',
        resizable: true
    },
    {
        title: "有效期至",
        dataIndex: "effectiveDate",
        key: 'effectiveDate',
        resizable: true
    },
    {
        title: "结算单号",
        dataIndex: "payNumber",
        key: 'payNumber',
        resizable: true
    },
    {
        title: "发票号",
        dataIndex: "invoiceNumber",
        key: 'invoiceNumber',
        resizable: true,
        ellipsis: true
    },
    {
        title: "返点率(%)",
        dataIndex: "pointRate",
        key: 'pointRate',
        align: "center"
    },
    {
        title: "税率(%)",
        dataIndex: "taxRate",
        key: 'taxRate',
        align: "center"
    },
    {
        title: "税额(元)",
        dataIndex: "taxAmount",
        key: 'taxAmount',
        align: "center"
    },
    {
        title: "含税均价(元)",
        dataIndex: "taxAveragePrice",
        key: 'taxAveragePrice',
        align: "center"
    },
    {
        title: "含税总额(元)",
        dataIndex: "taxTotalAmount",
        key: 'taxTotalAmount',
        align: "center"
    },
    {
        title: "无税均价(元)",
        dataIndex: "noTaxAveragePrice",
        key: 'noTaxAveragePrice',
        align: "center"
    },
    {
        title: "无税总额(元)",
        dataIndex: "noTaxTotalAmount",
        key: 'noTaxTotalAmount',
        align: "center"
    },
    {
        title: "零售价(元)",
        dataIndex: "retailPrice",
        key: 'retailPrice',
        align: "center"
    },
    {
        title: "购进数量",
        dataIndex: "num",
        key: 'num',
        align: "center"
    },
    {
        title: "操作人员",
        dataIndex: "username",
        key: 'username',
        align: "center"
    },
    {
        title: "结算金额(元)",
        dataIndex: "payAmount",
        key: 'payAmount',
        align: "center"
    },
    {
        title: "返点金额(元)",
        dataIndex: "pointAmount",
        key: 'pointAmount',
        align: "center",
        fixed: "right"
    },
    {
        title: "操作",
        dataIndex: "action",
        fixed: "right"
    }
])
const open = ref(false);
const title = ref("");
const formData = ref({});

function loadItems({page, itemsPerPage}) {
    loading.value = true;
    pageNo.value = page
    pageSize.value = itemsPerPage
    axios.post('/MedicineOrder/getMedicineOrderList', {
        page: page,
        pageSize: itemsPerPage,
        orderNumber: queryParams.value.orderNumber,
        startTime: queryParams.value.startTime ? moment(queryParams.value.startTime.$d).format("YYYY-MM-DD HH:mm:ss") : '',
        endTime: queryParams.value.endTime ? moment(queryParams.value.endTime.$d).format("YYYY-MM-DD HH:mm:ss"): ""
    }).then(({data}) => {
        items.value = data.data.records;
        totalItems.value = data.data.total;
        loading.value = false;
    })
}

const baseInfoListSelect = ref(null)
const basePointInfoListSelect = ref(null)
const baseInfoList = ref([]);
const basePointInfoList = ref([]);
onMounted(() => {
    loadItems({page: 1, itemsPerPage: pageSize.value});
    axios.post('/Medicine/getMedicineList', {
        page: 1,
        pageSize: 1000,
        goodsNumber: "",
        goodsName: "",
        commonName: "",
        startTime: "",
        endTime: ""
    }).then(({data}) => {
        baseInfoList.value = data.data.records
    })
    axios.post('/MedicinePoint/getMedicinePointList', {
        page: 1,
        pageSize: 1000,
        goodsNumber: "",
        goodsName: "",
        commonName: "",
        supplierName: "",
        startTime: "",
        endTime: ""
    }).then(({data}) => {
        basePointInfoList.value = data.data.records
    })
});

const dialogEnum = {
    update: "编辑",
    create: "新增"
}

function openData(data) {
    open.value = true
    title.value = data.orderName
    baseInfoListSelect.value = null
    basePointInfoListSelect.value = null
    axios.post("/MedicineOrder/getMedicineOrderInfo", {orderNumber: data.orderNumber}).then(res => {
        addList.value = res.data.data
    })
}

const filteredData = computed(() => {
    return addList.value.filter(item => item.status)
})

function submit() {
    confirmLoading.value = true
    let obj = {
        medicineOrderList: addList.value
    }
    obj.medicineOrderList.forEach(record => {
        record.noTaxTotalAmount = (record.noTaxAveragePrice * record.num).toFixed(2)
        record.taxTotalAmount = (record.taxAveragePrice * record.num).toFixed(2)
        record.taxAmount = (record.noTaxAveragePrice * record.num * (1 + (record.taxRate/100)) - record.noTaxAveragePrice * record.num).toFixed(2)
        record.pointAmount = (record.noTaxAveragePrice * record.num * (record.pointRate/100)).toFixed(2)
        record.payAmount = (record.noTaxAveragePrice * record.num * (1 + (record.taxRate/100)) - record.noTaxAveragePrice * record.num * (record.pointRate/100)).toFixed(2)
    })
    axios.post("/MedicineOrder/updateMedicineOrder", obj).then(res => {
        if(res.data.code == 0) {
            message.success('修改成功！')
            confirmLoading.value = false;
            open.value = false;
            loadItems({page: 1, itemsPerPage: pageSize.value});
        } else {
            confirmLoading.value = false;
            message.error(res.data.message)
        }
    }, err => {
        confirmLoading.value = false;
        message.error(err.data.message)
    })
}

function handleTabChange(pag){
    loadItems({page: pag.current, itemsPerPage: pag.pageSize})
}


function deleteList(val) {
    let obj = {
        orderNumber: val.orderNumber
    }
    axios.post('/MedicineOrder/disableMedicineOrder', obj).then(res => {
        if(res.data.code == 0) {
            message.success('删除成功！')
            loadItems({page: 1, itemsPerPage: pageSize.value});
        } else {
            message.error(res.data.message)
        }
    }, err => {
        message.error(err.data.message)
    })
}

function addListById() {
    if(!baseInfoListSelect.value || !basePointInfoListSelect.value) {
        message.error("请选择添加行！")
        return
    }
    baseInfoList.value.forEach(item => {
        if(item.medicineId == baseInfoListSelect.value) {
            let data = JSON.parse(JSON.stringify(item))
            data.status = true
            basePointInfoList.value.forEach(k => {
                if(k.medicinePointId == basePointInfoListSelect.value) {
                    let dataA = JSON.parse(JSON.stringify(k))
                    let addData = Object.assign({}, addList.value[0], Object.assign({}, data, dataA))
                    addList.value.push(addData)
                }
            })            
        }
    })
}

function handleResizeColumn(w, col) {
  col.width = w;
}

const totalNum = computed(() => {
    const num = addList.value.reduce((sum, record) => sum + (record.noTaxAveragePrice * record.num * (record.pointRate/100)), 0)
    return num.toFixed(2);
})
</script>

<template>
    <a-spin size="large" :spinning="loading">
        <a-card title="返点记录">
            <a-row style="margin-bottom: 15px;">
                <a-form
                layout="inline"
                :model="queryParams">
                    <a-form-item label="返点清单编码">
                        <a-input v-model:value="queryParams.orderNumber" placeholder="返点清单编码"  allow-clear @keyup.enter="loadItems({page: 1, itemsPerPage: pageSize})"></a-input>
                    </a-form-item>
                    <a-form-item label="开始时间">
                        <a-date-picker show-time v-model:value="queryParams.startTime" placeholder="开始时间"></a-date-picker>
                    </a-form-item>
                    <a-form-item label="结束时间">
                        <a-date-picker show-time v-model:value="queryParams.endTime" placeholder="结束时间"></a-date-picker>
                    </a-form-item>
                    <a-from-item>
                        <a-button @click="loadItems({page: 1, itemsPerPage: pageSize})">查询</a-button>
                    </a-from-item>
                </a-form>
            </a-row>
            <a-table
            @resizeColumn="handleResizeColumn"
            rowKey="medicinePointId"
            :dataSource="items"
            :columns="columns"
            :pagination="pagination"
            @change="handleTabChange">
                <template #bodyCell="{ column, text, record }">
                    <tempalte v-if="column.dataIndex == 'action' && !record.trueAmount">
                        <a @click="openData(record)">修改&nbsp;&nbsp;</a>
                        <a-popconfirm
                        title="确认删除该角色？"
                        okText="确认"
                        cancelText="取消"
                        @confirm="deleteList(record)">
                            <a style="color: red;">删除</a>                      
                        </a-popconfirm>
                    </tempalte>
                </template>
            </a-table>            
        </a-card>

        <a-modal
        v-model:open="open"
        :title="title"
        cancelText="关闭"
        okText="确定"
        width="76%"
        zIndex=1010
        :confirmLoading="confirmLoading"
        @ok="submit">
            <a-table
            @resizeColumn="handleResizeColumn"
            :dataSource="filteredData"
            :columns="columnsAdd"
            :scroll="{ x: 4000 }"
            :pagination="false">
                <template #bodyCell="{column, text, record, index}">
                    <template v-if="column.dataIndex == 'pointRate'">
                        <a-input v-model:value="record.pointRate"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'taxRate'">
                        <a-input v-model:value="record.taxRate"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'taxAveragePrice'">
                        <a-input v-model:value="record.taxAveragePrice"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'noTaxAveragePrice'">
                        <a-input v-model:value="record.noTaxAveragePrice"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'retailPrice'">
                        <a-input v-model:value="record.retailPrice"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'num'">
                        <a-input v-model:value="record.num"></a-input>
                    </template>
                    <template v-if="column.dataIndex == 'noTaxTotalAmount'">
                        <span>{{ (record.noTaxAveragePrice * record.num).toFixed(2) }}</span>
                    </template>
                    <template v-if="column.dataIndex == 'taxTotalAmount'">
                        <!-- <span>{{ (record.noTaxAveragePrice * record.num * (1 + (record.taxRate/100))).toFixed(2) }}</span> -->
                        <span>{{ (record.taxAveragePrice * record.num).toFixed(2) }}</span>
                    </template>
                    <template v-if="column.dataIndex == 'taxAmount'">
                        <span>{{ (record.noTaxAveragePrice * record.num * (1 + (record.taxRate/100)) - record.noTaxAveragePrice * record.num).toFixed(2) }}</span>
                    </template>
                    <template v-if="column.dataIndex == 'pointAmount'">
                        <span>{{ (record.noTaxAveragePrice * record.num * (record.pointRate/100)).toFixed(2) }}</span>
                    </template>
                    <template v-if="column.dataIndex == 'payAmount'">
                        <span>{{ (record.noTaxAveragePrice * record.num * (1 + (record.taxRate/100)) - record.noTaxAveragePrice * record.num * (record.pointRate/100)).toFixed(2) }}</span>
                    </template>
                    <template v-if="column.dataIndex == 'action'">
                        <a style="color: red;" @click="record.status = false">删除</a>
                    </template>
                </template>
                <template #summary>
                    <a-table-summary fixed>
                        <a-table-summary-row>
                            <a-table-summary-cell :index="0">
                                <div style="font-weight: 700;">返点总额</div>
                            </a-table-summary-cell>
                            <a-table-summary-cell :index="1" :col-span="20"></a-table-summary-cell>
                            <a-table-summary-cell :index="21">
                                <div style="text-align: center;font-weight: 700;">{{ totalNum }}</div>
                            </a-table-summary-cell>
                        </a-table-summary-row>
                    </a-table-summary>
                </template>
            </a-table>
            <a-select
            v-model:value="baseInfoListSelect"
            placeholder="请选择添加商品"
            show-search
            :options="baseInfoList"
            :fieldNames="{
                label: 'goodsName',
                value: 'medicineId'
            }"
            style="width: 200px;">
            </a-select>&nbsp;
            <a-select
            v-model:value="basePointInfoListSelect"
            placeholder="请选择添加供应商"
            show-search
            :options="basePointInfoList"
            :fieldNames="{
                label: 'supplierName',
                value: 'medicinePointId'
            }"
            style="width: 200px;">
            </a-select>&nbsp;
            <a-button @click="addListById">添加行</a-button>
        </a-modal>
    </a-spin>
</template>

<style scoped lang="less">

</style>
